
package com.zwy.filter;

import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xkcoding.http.support.Http;
import com.zwy.domain.entity.LoginUser;
import com.zwy.utils.JwtUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author zwy
 * @version 1.0
 * @description: JwtAuthorizeFilter
 * @date 2025/9/18 11:54
 * @action
 * 用于拦截请求，验证JWT Token的有效性。
 */
@Component
public class JwtAuthorizeFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //提取请求头的header
        String authorization = request.getHeader("Authorization");
        //解析 jwt
        DecodedJWT jwt = jwtUtils.resolveJwt(authorization);
        if(!ObjectUtils.isEmpty(jwt)){
            //获取UserDetails
            LoginUser user = (LoginUser) jwtUtils.toUser(jwt);
            //创建认证对象
            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
            //保存认证详细过程
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //验证通过，设置上下文中
            SecurityContextHolder.getContext().setAuthentication(authentication);

        }
        //继续过滤
        filterChain.doFilter(request,response);
    }

}
